<?php

# http://projects:8081/cdapp-2kt-api/api/global_notes_handler.php
include_once '_portal.php';

# SELECT * FROM `2kt_global_notes` WHERE 1
# UPDATE `2kt_global_notes` SET `number`='[value-1]',`text`='[value-2]',`type`='[value-3]',`until`='[value-4]' WHERE 1
# INSERT INTO `2kt_global_notes`(`number`, `text`, `type`, `until`) VALUES ('[value-1]','[value-2]','[value-3]','[value-4]')
# DELETE FROM `2kt_global_notes` WHERE 0

$action = isset($_GET['action']) ? $_GET['action'] : '';

if ($action == "add") {
  handle_add($post);
} elseif ($action == "save") {
  handle_save($post);
} elseif ($action == "delete") {
  handle_delete($post);
} else {
  handle_get();
}

die();

function handle_get() {
  $date = date("Y-m-d H:i:s", time() - 48 * 3600);
  $sql = "SELECT * FROM `2kt_global_notes` WHERE `until` >= '$date' ORDER BY `number` DESC LIMIT 50";
  $result = exec_sql($sql);
  if ($result) {
    output([
      'action' => 'get',
      'result' => $result,
      'success' => true,
      'sql' => $sql,
    ]);
  } else {
    output([
      'action' => 'get',
      'result' => [],
      'success' => false,
      'sql' => $sql,
    ]);
  }
  return null;
}

function handle_add($data) {
  $sql = "INSERT INTO `2kt_global_notes`(`text`, `type`, `until`) VALUES ('{$data->text}','{$data->type}','{$data->until}')";
  $sql2 = "SELECT LAST_INSERT_ID() as lastID";
  $result = exec_sql_array([$sql, $sql2]);
  if ($result[0]) {
    output([
      'action' => 'add',
      'result' => $result[1][0]['lastID'],
      'success' => true,
      'data' => $data,
      'sql' => $sql,
    ]);
    return null;
  } else {
    output([
      'action' => 'add',
      'result' => -1,
      'success' => false,
      'data' => $data,
      'sql' => $sql,
    ]);
    return null;
  }
}

function handle_save($data) {
  $sql = "UPDATE `2kt_global_notes` SET `text`='{$data->text}',`type`='{$data->type}',`until`='{$data->until}' WHERE `number`={$data->number}";
  $result = exec_sql($sql);
  output([
    'action' => 'save',
    'result' => $result,
    'success' => $result,
    'data' => $data,
    'sql' => $sql,
  ]);
  return $result;
}

function handle_delete($data) {
  $sql = "DELETE FROM `2kt_global_notes` WHERE `number` = {$data->number}";
  $result = exec_sql($sql);
  output([
    'action' => 'delete',
    'result' => $result,
    'success' => $result,
    'data' => $data,
    'sql' => $sql,
  ]);
  return $result;
}